#include<iostream>
#include<string.h>
using namespace std;

class mystring
{
    friend ostream& operator<<(ostream &out,mystring ob);
    friend istream& operator>>(istream &in,mystring &ob);
public:
    int getsize(void);
    mystring();
    mystring(char *str);
    mystring(mystring &str);
    ~mystring();

    char& operator[](int pos)
    {
        if(pos>size&&pos<0)
        {
            exit(-1);
        }
        return this->str[pos];
    };

    mystring& operator+(mystring ob)
    {
        char *tem;
        tem=this->str;
        this->size=this->size+ob.size;
        this->str=new char[this->size+1];
        memset(this->str,0,this->size);
        strcat(this->str,tem);
        strcat(this->str,ob.str);
        return *this;
    };
    void operator=(mystring ob)
    {
        if(this->str!=0)
        {
            delete[] this->str;
            this->str=NULL;
        }
        this->size=ob.size;
        this->str=new char[this->size+1];
        memset(this->str,0,this->size+1);
        strcpy(this->str,ob.str);
    };
    void operator=(char *ob)
    {
        if(this->str!=0)
        {
            delete[] this->str;
            this->str=NULL;
        }
        this->size=strlen(ob);
        this->str=new char[this->size+1];
        memset(this->str,0,this->size+1);
        strcpy(this->str,ob);
    };

private:
    char * str;
    int size;
};

ostream& operator<<(ostream &out,mystring ob)
{
    out<<ob.str<<endl;
    return out;
};

istream& operator>>(istream &in,mystring &ob)
{
    if(ob.str!=NULL)
    {
        delete[] ob.str;
        ob.str=NULL;
    }
   char tem[128]="";
   in>>tem;
   ob.size=strlen(tem);
   ob.str=new char[ob.size+1];
   memset(ob.str,0,ob.size);
   strcpy(ob.str,tem);
   return in;
}

int main()
{
    mystring str1("hello");
    cout<<str1[1]<<endl;
    //str1[1]='j';
    cout<<str1<<endl;
    mystring str2;
    cin>>str2;
    cout<<str2<<endl;
    mystring str3("world");
    cout<<str1+str2<<endl;
    //mystring str4(str3);    //这个是拷贝构造，可以调用拷贝构造

    mystring str4;    //这个调用默认构造
    str4=str3;        //进行赋值操作，所以str4与str3是指向同一个空间，造成空间泄露和同一片空间重复释放的问题。
    cout<<str4<<endl;
    str4="wowow";           //需要重写“=”。 
    cout<<str4<<endl;
    system("pause");
    return 0;
    
}

int mystring::getsize(void)
{
    return size;
}
//构造函数：申请空间
    mystring::mystring()
    {
        this->size=0;
        this->str=NULL;
    }
    mystring::mystring(char *str)       //传一个字符串
    {
        this->size=strlen(str);
        this->str=new char[size+1];
        memset(this->str,0,this->size+1);
        strcpy(this->str,str);

    }
    mystring::mystring(mystring &str)   //因为有指针成员 一定要人为拷贝构造
    {
        this->size=str.size;
        this->str=new char[this->size+1];
        memset(this->str,0,this->size+1);
        strcpy(this->str,str.str);
    }
    mystring::~mystring()              //析构函数：释放空间
    {
        if(this->str!=NULL)
        {
            delete[] str;
            this->str=NULL;
        }
    }